//
// app.js
// @author Kevin Zhuang
// @version 1.0.12
// @since 07.08.2014
//

var CapFirstLetter = function(string){
   return string.charAt(0).toUpperCase() + string.slice(1);
}





// MAIN ENTRY
//=======================================================================
var config        = require('./config');
var express       = require('express');
var mongoose      = require('mongoose');
var passport      = require('passport');
var flash         = require('connect-flash');
//var prompt        = require('prompt');

//=======================================================================
var favicon       = require('serve-favicon');
var multer        = require('multer');
var bodyParser    = require('body-parser');
var cookieParser  = require('cookie-parser');
var session       = require('express-session');
var csrf          = require('csurf');

// global variable
Domain = require('./club.domains');

//=======================================================================
var my_csrf = function(req, res, next){
   var csrfEnable = true;
   var csrfIgnorePath = new Array('/users/login', '/users/signup', '/messages/list', '/ajax', '/clubs/list', '/upload');
   if(csrfIgnorePath.indexOf(req.path) != -1)
      csrfEnable = false;
   
   if(csrfEnable) csrf()(req, res, next);
   else           next();
};

//=======================================================================
require('./passport_config')(passport);


//=======================================================================
var app = express();
app.listen(config.web.port);  //$sudo PORT=8080 node app.js
app.locals.pretty = true;

app.set('view engine', 'jade');
app.set('views', __dirname + '/views');
app.use(express.static(__dirname + '/public')); //js css img fonts...
app.use(favicon(__dirname + '/public/img/favicon.ico'));

app.use(cookieParser());
//app.use(session( {secret: 'my_super_secrete_word'} ));
app.use(session( {secret: 'my_super_secrete_word', resave: true, saveUninitialized: true } ));
//app.use(bodyParser());
app.use(bodyParser.urlencoded({extended: true}));
app.use(bodyParser.json());
app.use(multer({dest: "./public/upload/"}));

app.use(my_csrf);

app.use(passport.initialize());
app.use(passport.session());
app.use(flash());

app.use(require('./remember_me.js'));  // my cookie handler
//prompt.start();


//=======================================================================
//mongoose.connect('192.168.2.10:27017/db', function(err){
mongoose.connect(config.mongodb.url, function(err){
   if(err){
      console.log('Cannot connect to mongodb');
      process.exit(1);
   }
   console.log('Successfully connected to the mongodb');

   //========= S E T U P   A   S U P E R   A D M I N   U S E R ===========
   Domain.User.find({role: 'admin'}).exec(function(err, usrs){                 
      if(err) throw err;                                                
      if(usrs && usrs.length > 0) return;                               
      
      //var schema={properties:{email: {required:true}, password:{hidden:true}}};
      //prompt.get(schema, function(err, usr){
      Domain.User.find({email: config.admin.email}).exec(function(err, docs){
         if(docs && docs.length > 0) return;
         var admin = new User();
         admin.local.email    = config.admin.email;
         admin.local.password = admin.generateHash(config.admin.password);
         admin.firstname      = CapFirstLetter(config.admin.firstname);
         admin.lastname       = CapFirstLetter(config.admin.lastname);
         admin.role           = 'admin';
         admin.save(function(err) {});
      });
      //});
   });                                                                  
   //=====================================================================

});


//=======================================================================
require('./router.js')(app, passport);

